package com.whz.gateway.common.log;

import com.whz.gateway.common.util.AttributeUtils;
import com.whz.gateway.common.util.GatewayIpUtils;
import lombok.experimental.UtilityClass;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import java.util.Date;

/**
 * @author whz
 * @date 2021/8/30
 */
@UtilityClass
public class LogUtils {

    public GatewayLog printLog(final ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String requestPath = request.getPath().pathWithinApplication().value();
        Route route = AttributeUtils.getRouterAfterStrip(exchange);
        GatewayLog gatewayLog = new GatewayLog();
        gatewayLog.setSchema(request.getURI().getScheme());
        gatewayLog.setRequestMethod(request.getMethodValue());
        gatewayLog.setRequestPath(requestPath);
        gatewayLog.setTargetServer(route.getId());
        gatewayLog.setRequestTime(new Date());
        gatewayLog.setUserAgent(request.getHeaders().getFirst(HttpHeaders.USER_AGENT));
        gatewayLog.setIp(GatewayIpUtils.getRemoteIp(request));
        return gatewayLog;
    }
}